package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jt
 * @date 2021/4/12 18:28
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmUserDto wmUserDto) {
//        1.检查参数
        if (wmUserDto == null || StringUtils.isBlank(wmUserDto.getName()) || StringUtils.isBlank(wmUserDto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码错误");
        }
//        2.查询对应的自媒体用户
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, wmUserDto.getName()));
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"对应的自媒体用户不存在");
        }
//        2.1 检查status状态,如果为9才能登录
        if (wmUser.getStatus() != AdminConstants.AD_USER_ISSTATUS) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_NO);
        }
//        3.检查密码是否正确
        String password = DigestUtils.md5DigestAsHex((wmUserDto.getPassword() + wmUser.getSalt()).getBytes());
        if (!wmUser.getPassword().equals(password)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        修改最近的登录时间
        wmUser.setCreatedTime(new Date());
        updateById(wmUser);
//        4.返回jwt结果
        Map map = new HashMap();
        map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));
        wmUser.setPassword("");
        wmUser.setSalt("");
        map.put("user",wmUser);
        return ResponseResult.okResult(map);
    }

}
